import datetime
from rest_framework.views import APIView
from rest_framework import viewsets, mixins
from django.http import HttpResponse
from .client import ZXClient
from .models import OrderRecord
from .serializers import PaySerializers, ZxUserSerializers, MyLoginSerializer
from rest_framework import status
from rest_framework.response import Response
from rest_framework_jwt.views import JSONWebTokenAPIView
from rest_framework_jwt.settings import api_settings
from apps.czb.models import Orders as CzbOrders

jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER

zx_client = ZXClient()


class NotifyOrder(APIView):
    def post(self, request):
        data = self.request.data
        msgBody = data.get("msgBody")
        msgSignature = data.get("msgSignature")
        retMsg = data.get("retMsg")
        print(data, "中信数据通知")
        result = zx_client.verify_with_rsa(msgBody, msgSignature)
        print(result, "中信result")
        if result:
            print(msgBody, "中信支付通知请求数据")
            originSerialNo = msgBody.get("originSerialNo")
            if not originSerialNo:
                return HttpResponse(200)
            amount = msgBody.get("amount")
            originTranTime = msgBody.get("originTranTime")
            try:
                order_instance = OrderRecord.objects.get(out_trade_no=originSerialNo)
                czb_order_instance = CzbOrders.objects.get(out_trade_no=originSerialNo)
                out_trade_no = czb_order_instance.out_trade_no
                instance = OrderRecord.objects.get_order_record_instance(out_trade_no)
                params, response = zx_client.search_order(out_trade_no, originTranTime)
                # 更新数据
                if response.get("msgBody").get("tranResult") == "TRADE_SUCCESS" and order_instance.totalAmount == int(
                        amount):
                    czb_order_instance.update_pay_result(1, pay_type=6)  # 1:支付成功
                    czb_order_instance.save()
                    czb_order_instance.refresh_from_db()
                instance.update_search_response(**response.get("msgBody"))
                return HttpResponse(200)
            except Exception as e:
                raise Exception("zhong xin notify error %s" % e)
        else:
            return HttpResponse("ERROR")


class PayViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
    serializer_class = PaySerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        headers = {"mweb_url": serializer.pay_url, "out_trade_no": instance.orderKey}
        print(headers, "中信支付返回给前端")
        return Response(headers, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()


# 授权登录
class OauthViewSet(JSONWebTokenAPIView):
    serializer_class = ZxUserSerializers

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            if user and token:
                response_data = jwt_response_payload_handler(token, user, request)
                response = Response(response_data)
                if api_settings.JWT_AUTH_COOKIE:
                    expiration = (datetime.datetime.utcnow() +
                                  api_settings.JWT_EXPIRATION_DELTA)
                    response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                        token,
                                        expires=expiration,
                                        httponly=True)
                return response
            else:
                openid = serializer.object.get("openid")
                return Response({"openid": openid})

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 注册登录
class ZxLoginViewSet(JSONWebTokenAPIView):
    serializer_class = MyLoginSerializer
